package org.micode.common.file;

import org.micode.common.utils.FileExtUtils;
import org.micode.common.utils.OsProcessUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ConvertTool {

    public static String FILE_EXT_MP3 = ".mp3";

    public static boolean convertFile(String filenamePrefix,
                                      String fileUrl,
                                      String extName,
                                      String convertToolCmd,
                                      int codecType,
                                      int timeoutSeconds) {
        return (doConvertFile(filenamePrefix, fileUrl, extName, convertToolCmd, codecType, timeoutSeconds) > 0);
    }

    /**
     * 转换文件格式的处理
     *
     * @return
     */
    private static Integer doConvertFile(String filenamePrefix,
                                         String fileUrl,
                                         String extName,
                                         String convertToolCmd,
                                         int codecType,
                                         int timeoutSeconds) {
        if (FileExtUtils.existFile(convertToolCmd)) {
            // 先生成新格式的文件
            if (convertAudioFile(convertToolCmd, filenamePrefix, fileUrl, codecType, timeoutSeconds)) {
                if (FileExtUtils.existFile(fileUrl + extName)) {
                    return 1;
                }
            }
        }
        return 0;
    }

    private static boolean convertAudioFile(String convertTool, String prefix, String fileUrl,
                                            int codecType, int timeoutSeconds) {
        String cmd = convertTool + " " + fileUrl + " " + prefix + " " + codecType;
        return OsProcessUtils.exec(cmd, timeoutSeconds, "Transform file format");
    }

}
